<script setup lang="ts">
import { showConfirmDialog, showSuccessToast } from "vant";
import { ref } from "vue";
import { useRouter } from "vue-router";
import { API } from "../api";
import { MUserEntity, XYCOrderEntity } from "../api/_Api";
import { getStorage } from "../utils/cache";
import { useUserList } from "./useUserList";
import { watch } from "vue";
const router = useRouter();
const push = router.push;
const list = ref([] as XYCOrderEntity[]);
const loading = ref(false);
const finished = ref(false);
const userInfo = JSON.parse(getStorage("userInfo") || "{}") as MUserEntity;
const type = userInfo.type !== "manager" ? "xyc" : "manager";
const onLoad = async () => {
  console.log("2222");
  const brand = form.value.brand ? form.value.brand : undefined
  const userId = form.value.userId ? form.value.userId : undefined
  const {
    data: { data },
  } = await API.orderControllerXycFind({
    page: form.value.page++,
    size: form.value.size,
    brand,
    userId,
  });
  console.log("🚀 ~ onLoad ~ data:", data);
  list.value.push(...(data?.list || []));
  form.value.total = data?.total || 0;
  showSuccessToast({ message: "加载成功~" });
  // 加载状态结束
  loading.value = false;

  // 数据全部加载完成
  if (list.value.length >= form.value.total) {
    finished.value = true;
  }
};
const form = ref({ page: 1, size: 20, total: 0, userId: "", brand: "" });
function showConfirm(id: string) {
  showConfirmDialog({
    title: "提示",
    message: "你确认要删除该行记录吗？",
  })
    .then(async () => {
      // on confirm
      await API.orderControllerXycDelete({ id });
      showSuccessToast({ message: "删除成功~" });
      form.value.page = 1;
      form.value.total = 0;
      list.value = [];
      setTimeout(() => {
        onLoad();
      }, 1000);
    })
    .catch(() => {
      // on cancel
    });
}
const span = {
  xyc: { index: 2, name: 6, phone: 7, address: 9 },
  manager: { index: 2, name: 4, phone: 5, address: 5, brand: 6, exec: 2 },
} as any;

const result = ref({ brandText: "", userText: "" });
const showPicker = ref(false);
const showUserPicker = ref(false);
const brandColumns = ref([{ text: '全部', value: '' }] as { text: string; value: string }[]);
const userColumns = ref([{ text: '全部', value: '' }] as { text: string; value: string }[]);

const onConfirm = ({ selectedOptions }: any) => {
  result.value.brandText = selectedOptions[0]?.text;
  form.value.brand = selectedOptions[0]?.value;
  showPicker.value = false;
  form.value.page = 1;
  form.value.total = 0;
  list.value = [];
  onLoad();
};
const onUserConfirm = ({ selectedOptions }: any) => {
  result.value.userText = selectedOptions[0]?.text;
  form.value.userId = selectedOptions[0]?.value;
  showUserPicker.value = false;
  form.value.page = 1;
  form.value.total = 0;
  list.value = [];
  onLoad();
};
const { userList } = useUserList();

watch(
  () => userList.value,
  (v) => {
    const brand = new Set() as Set<string>;
    v.forEach((d) => {
      d.realName && brand.add(d.realName);
      userColumns.value.push({ text: d.nickName || "", value: d.id || "" });
    });
    brand.forEach((d) => {
      brandColumns.value.push({ text: d, value: d });
    });
  }
);
async function down() {
  const r = await API.orderControllerGetFile({ ...form.value })
  const t = await r.blob()
  var a = document.createElement('a');
  var url = window.URL.createObjectURL(t);   // 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
  var filename = r.headers.get('Content-Disposition');
  a.href = url;
  a.download = (filename || '').split('"')[1];
  a.click();
  window.URL.revokeObjectURL(url);
}
function logout() {
  push('/login')
}
</script>

<template>
  <div class="inputlist">
    <div class="exec">
      <div class="from">
        <div class="from-item" v-if="type === 'manager'">
          <van-field v-model="result.brandText" is-link readonly name="picker" label="" placeholder="筛选品牌"
            @click="showPicker = true" />
        </div>
        <div class="from-item" v-if="type === 'manager'">
          <van-field v-model="result.userText" is-link readonly name="picker" label="" placeholder="筛选店员"
            @click="showUserPicker = true" />
        </div>
      </div>
      <van-popup v-model:show="showPicker" position="bottom">
        <van-picker :columns="brandColumns" @confirm="onConfirm" @cancel="showPicker = false" />
      </van-popup>
      <van-popup v-model:show="showUserPicker" position="bottom">
        <van-picker :columns="userColumns" @confirm="onUserConfirm" @cancel="showUserPicker = false" />
      </van-popup>
    </div>
    <van-button type="warning" size="normal" round @click="logout" icon="./logout.png" class="logout"></van-button>
    <!-- <van-button type="primary" size="normal" round @click="push('/input')" icon="plus" class="add"></van-button> -->
    <van-button type="primary" size="normal" round @click="down" class="down" icon="down"
      v-if="type === 'manager'"></van-button>
    <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" class="list">
      <van-row class="li">
        <van-col :span="span[type].index" class="td">序号</van-col>
        <van-col :span="span[type].name" class="td">贵宾姓名</van-col>
        <van-col :span="span[type].phone" class="td">贵宾电话</van-col>
        <van-col :span="span[type].address" class="td">小区地址</van-col>
        <van-col :span="span[type].brand" class="td" v-if="type === 'manager'">品牌</van-col>
        <van-col :span="span[type].exec" class="td" v-if="type === 'manager'">操作</van-col>
      </van-row>
      <van-row v-for="(item, index) in list" :key="item.id" :title="item.name" class="li">
        <van-col :span="span[type].index" class="td">{{ index + 1 }}</van-col>
        <van-col :span="span[type].name" class="td">{{ item.name }}</van-col>
        <van-col :span="span[type].phone" class="td">{{ item.phone }}</van-col>
        <van-col :span="span[type].address" class="td">{{
          item.address
        }}</van-col>
        <van-col :span="span[type].brand" class="td" v-if="type === 'manager'">{{ item.brand }}</van-col>
        <van-col :span="span[type].exec" class="td" v-if="type === 'manager'"><van-button icon="cross" type="primary"
            size="mini" @click="showConfirm(item.id as string)"></van-button></van-col>
      </van-row>
    </van-list>
  </div>
</template>

<style scoped lang="less">
.exec {
  display: flex;
  justify-content: space-between;
  padding: 0 20px 0 0;
  align-items: center;

  .total {
    // font-size: 12px;
  }
}

.li {
  padding: 10px 10px;
  align-items: center;

  .td {
    padding-right: 10px;
  }
}

.from {
  display: flex;
}

.from-item {
  display: inline-block;
  width: 30vw;
}

.add {
  position: fixed;
  right: 30px;
  bottom: 30vw;
  height: 40px;
  width: 40px;
}

.down {
  position: fixed;
  right: 30px;
  bottom: 45vw;
  height: 40px;
  width: 40px;
}

.logout {
  position: fixed;
  right: 30px;
  bottom: 45vw;
  height: 40px;
  width: 40px;
}
</style>
